document.getElementById("nodeForm").addEventListener("submit", async (e) => {
  e.preventDefault();
  const filePath = document.getElementById("fileInput").value;

  const formData = new FormData();
  formData.append("file_path", filePath);

  const res = await fetch("/start_node", { method: "POST", body: formData });
  const data = await res.json();
  document.getElementById("nodeStatus").innerText = data.message;
});

async function loadTopics() {
  const res = await fetch("/topics");
  const data = await res.json();
  const list = document.getElementById("topics");
  list.innerHTML = "";
  data.topics.forEach(([name, type]) => {
    const li = document.createElement("li");
    li.innerText = `${name} (${type})`;
    list.appendChild(li);
  });
}

document.getElementById("pubForm").addEventListener("submit", async (e) => {
  e.preventDefault();
  const topic = document.getElementById("topicName").value;
  const msg = document.getElementById("msg").value;

  const formData = new FormData();
  formData.append("topic", topic);
  formData.append("msg", msg);

  const res = await fetch("/publish", { method: "POST", body: formData });
  const data = await res.json();
  document.getElementById("pubStatus").innerText = data.message;
});

function subscribeTopic() {
  const topic = document.getElementById("subTopic").value;
  const ws = new WebSocket(`ws://${window.location.host}/ws/${topic}`);
  const subDiv = document.getElementById("subMessages");

  ws.onmessage = (event) => {
    const p = document.createElement("p");
    p.innerText = `[${topic}] ${event.data}`;
    subDiv.appendChild(p);
  };
}